package com.jacobson.huobi.threads

import com.jacobson.huobi.entities.events.LoginEvent
import com.jacobson.huobi.entities.vo.LoginRespVo
import com.jacobson.huobi.utils.TokenStorageUtil
import org.simple.eventbus.EventBus

/**
 * 定时刷新线程
 */
object TokenThread {

    var tokenThread: Thread? = null
    var loginRespVo: LoginRespVo? = null
    var isRefreshToken: Boolean = true
    var refresh = false

    //access

    //refresh

    private val refreshTime: Long = 30 * 1000 //30s

    private val expireTime: Long = 24 * 60 * 60 * 1000 * 1//1天
    private val expireTime1 = 90 * 1000 //90s

    /**
     * 启动线程
     */
    fun start() {
        isRefreshToken = true
        if (tokenThread != null) {
            try {
                tokenThread!!.start()
            } catch (e: Exception) {
                initThread()
            }
        } else {
            initThread()
        }

    }

    /**
     * 停止线程
     */
    fun stop() {
        isRefreshToken = false
        tokenThread = null
    }

    /**
     * 初始刷线程
     */
    fun initThread() {
        tokenThread = Thread {
            while (isRefreshToken) {
                loginRespVo = TokenStorageUtil.read()
                if (loginRespVo != null && (System.currentTimeMillis() + (refreshTime * 2)> (loginRespVo!!.refreshTimes + expireTime))) {
                    isRefreshToken = false;
                    EventBus.getDefault().post(LoginEvent(2, null))
                }
                if (loginRespVo == null) {
                    isRefreshToken = false
                }
                Thread.sleep(refreshTime)
            }
        }
        tokenThread!!.start()
    }

}